package longrise.phone.com.bjjt_henan.compensate;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.GridView;
import android.widget.TextView;

import com.longrise.LEAP.Base.Objects.EntityBean;
import com.longrise.android.FormParameter;
import com.longrise.android.FrameworkManager;
import com.longrise.android.LFView;
import com.longrise.android.loaddata.newloaddata.LoadDataManagerCar;
import com.longrise.android.loaddata.newloaddata.LoadDataManagerFather;
import com.longrise.bjjt.BaseApplication;
import com.longrise.bjjt.util.FileUtils;
import com.longrise.bjjt.util.StringUtils;
import com.longrise.bjjt.util.UiUtil;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import longrise.phone.com.bjjt_henan.Adapter.AccidentLoadPicAdapter;
import longrise.phone.com.bjjt_henan.Constant.URLConstant;
import longrise.phone.com.bjjt_henan.MainActivity;
import longrise.phone.com.bjjt_henan.R;
import longrise.phone.com.bjjt_henan.Utils.CommontUtils;
import longrise.phone.com.bjjt_henan.Utils.UiUtils;

/**
 * 上传事故照片界面，Created by Administrator on 2016/5/12.
 */
public class NewLossLoadPicView extends LFView implements View.OnClickListener,
        MainActivity.OnActivityReturnBitmap, AdapterView.OnItemClickListener {

    public static final int SIZE = 5;//拍照总数目

    private Context context;
    private View view;
    private GridView otherGView;
    private GridView myGView;
    private Button mBtn;
    private String caseNo;
    private BaseApplication mApplication;
    private EntityBean[] unqualifylist;//审核失败的图片集合
    private EntityBean[] isqualifylist;//审核通过的图片集合
    private int fromWhere;//0是正常的跳转，1是照片审核后跳转来的,审核后过来的，要将已经上传成功的照片展示出来
    private List<EntityBean> otherPicLists;//对方显示的图片集合
    private List<EntityBean> myPicLists;//己方显示的图片集合
    private AccidentLoadPicAdapter otherAdapter;
    private AccidentLoadPicAdapter myAdapter;
    private EntityBean curBean;//当前点击的选项
    private List<Runnable> loadPics;//上传图片的队列
    private int curSize = 0;// 当前已上传的总数目
    private Dialog processDialog;
    private String isSingle;

    public NewLossLoadPicView(Context c, String caseNo, int fromWhere) {
        super(c);
        this.context = c;
        this.caseNo = caseNo;
        this.mApplication = (BaseApplication) c.getApplicationContext();
        this.fromWhere = fromWhere;
        if (context instanceof MainActivity) {
            ((MainActivity) context).setOnActivityReturnBitmap(this);
        }
    }

    public void setUnqualifylist(EntityBean[] unqualifylist) {
        this.unqualifylist = unqualifylist;
    }

    public void setIsqualifylist(EntityBean[] isqualifylist) {
        this.isqualifylist = isqualifylist;
    }

    //设置事故时单车还是双车类型
    public void setCaseType(String isSingle) {
        this.isSingle = isSingle;
    }

    @Override
    public FormParameter getFormParameter() {
        return null;
    }

    @Override
    public View getView() {
        return view;
    }

    @Override
    public void init() {
        setShowtitle(false);
        initViews();
        initValues();
    }

    private Handler myHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (view == null) {
                return;
            }
            UiUtils.changeText("(" + curSize + "/" + loadPics.size() + ")" + "");
            if (msg.what != loadPics.size()) {
                if (curSize == 1) {// 第一张上传成功
                    for (int i = 1; i < loadPics.size(); i++) {
                        myHandler.post(loadPics.get(i));
                    }
                }
            } else {
                if (null != processDialog) {
                    if (processDialog.isShowing()) {
                        processDialog.dismiss();
                    }
                }
                curSize = 0;//初始化i

                //进入定损审核界面
                AccidentCheckView accidentcheckview = new AccidentCheckView(context, caseNo, 1);
                FrameworkManager.getInstance().showNewForm(context, accidentcheckview);
            }
        }
    };

    //初始化事故布局及注册事件
    public void initViews() {
        if (context == null) {
            return;
        }
        view = LayoutInflater.from(context).inflate(R.layout.view_newloss_loadpic, null);
        if (view == null) {
            return;
        }
        //标题栏
        TextView titleTV = (TextView) view.findViewById(R.id.tv_title);
        titleTV.setText("上传车辆受损照片");
        view.findViewById(R.id.hn_btn_back).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                closeForm();
                OnDestroy();
            }
        });
        otherGView = (GridView) view.findViewById(R.id.newloss_gridview_other);
        myGView = (GridView) view.findViewById(R.id.newloss_gridview_my);
        mBtn = (Button) view.findViewById(R.id.newloss_btn_load);

        myAdapter = new AccidentLoadPicAdapter(context);
        myAdapter.setIsSingle(isSingle);
        myGView.setAdapter(myAdapter);
        if (TextUtils.equals(isSingle, "0")) {//单车隐藏对方
            view.findViewById(R.id.newloss_ll).setVisibility(View.GONE);
        } else {
            otherAdapter = new AccidentLoadPicAdapter(context);
            otherAdapter.setIsSingle(isSingle);
            otherGView.setAdapter(otherAdapter);
        }
        regEvent(true);
    }

    private void initValues() {
        if (!TextUtils.equals(isSingle, "0")) {
            if (otherPicLists == null) {
                otherPicLists = new ArrayList<EntityBean>();
            } else {
                otherPicLists.clear();
            }
        }
        if (myPicLists == null) {
            myPicLists = new ArrayList<EntityBean>();
        } else {
            myPicLists.clear();
        }
        if (fromWhere == 0) {//拍摄定损照片
            addDefaultData(myPicLists, "12");
            if (null != otherPicLists) {
                addDefaultData(otherPicLists, "11");
            }
        } else if (fromWhere == 1) {//审核失败重拍
            if (null == unqualifylist || unqualifylist.length <= 0) {//该情况属于数据不正常
                addUrlData();
            } else if (unqualifylist.length == 1) {//单方审核失败
                int imagetype = (int) unqualifylist[0].get("imagetype");
                if (imagetype == 11) {//对方失败
                    addDefaultData(otherPicLists, "11");
                } else if (imagetype == 12) {//己方失败
                    addDefaultData(myPicLists, "12");
                }
                addUrlData();
            } else {//双方审核失败
                addDefaultData(otherPicLists, "11");
                addDefaultData(myPicLists, "12");
            }
        }

        myAdapter.setLists(myPicLists);
        myAdapter.notifyDataSetChanged();
        if (null != otherPicLists) {//双车情况
            otherAdapter.setLists(otherPicLists);
            otherAdapter.notifyDataSetChanged();
        }
    }

    /**
     * 添加默认数据
     *
     * @param lists
     * @param type：11表示对方图片类型;12表示己方图片类型
     */
    private void addDefaultData(List<EntityBean> lists, String type) {
        if (lists == null) {
            return;
        }
        //添加默认的首项
        EntityBean mBean = new EntityBean();
        mBean.set("type", type);
        lists.add(mBean);
        mBean = null;
        //添加+号项
        EntityBean aBean = new EntityBean();
        aBean.set("type", "-1");
        lists.add(aBean);
        aBean = null;
    }

    //添加审核通过的数据
    private void addUrlData() {
        if (isqualifylist == null) {
            return;
        }
        for (int i = 0; i < isqualifylist.length; i++) {
            EntityBean bean = new EntityBean();
            int imagetype = (int) isqualifylist[i].get("imagetype");
            String imageurl = (String) isqualifylist[i].get("imageurl");
            bean.set("type", String.valueOf(imagetype));
            bean.set("url", imageurl);
            if (imagetype == 11) {
                otherPicLists.add(bean);
            } else if (imagetype == 12) {
                myPicLists.add(bean);
            }
            bean = null;
        }
    }

    private void regEvent(boolean b) {
        if (mBtn != null) {
            mBtn.setOnClickListener(b ? this : null);
        }
        if (null != otherGView) {
            otherGView.setOnItemClickListener(b ? this : null);
        }
        if (null != myGView) {
            myGView.setOnItemClickListener(b ? this : null);
        }
    }


    @Override
    public void refresh() {

    }

    @Override
    public void refreshByTime() {

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.newloss_btn_load:
                if (null != otherPicLists && !checkTakePhoto(otherPicLists)) {
                    if (fromWhere == 0) {
                        UiUtil.showToast(getContext(), "请对方拍摄完照片后进行下一步");
                    } else {
                        UiUtil.showToast(context, "请重新拍摄对方车辆受损部位");
                    }
                    return;
                }
                if (!checkTakePhoto(myPicLists)) {
                    if (fromWhere == 0) {
                        if (TextUtils.equals(isSingle, "0")) {
                            UiUtil.showToast(context, "请拍摄车辆受损照片");
                        } else {
                            UiUtil.showToast(getContext(), "请本方拍摄完照片后进行下一步");
                        }
                    } else {
                        UiUtil.showToast(context, "请重新拍摄己方车辆受损部位");
                    }
                    return;
                }
                //上传照片
                processDialog = UiUtils.showProcessDialogPro(getContext(), "正在上传");
                uploadImgInfo();
                break;
            default:
                break;
        }
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        curBean = null;
        String toast = "";
        int requestCode = 0;
        switch (parent.getId()) {
            case R.id.newloss_gridview_other:
                curBean = otherPicLists.get(position);
                toast = "对方照片已经审核通过，不需要重新拍摄！";
                requestCode = 11;
                break;
            case R.id.newloss_gridview_my:
                curBean = myPicLists.get(position);
                toast = "己方照片已经审核通过，不需要重新拍摄！";
                requestCode = 12;
                break;
        }
        String url = curBean.getString("url");
        if (!TextUtils.isEmpty(url)) {
            UiUtil.showToast(context, toast);
            return;
        }
        String type = curBean.getString("type");
        //启动相机拍照
        switch (Integer.valueOf(type)) {
            case 11:
                getCamera("受损部位", "(请确保道路标线在拍摄画面中。)", R.drawable.car_8, requestCode);
                break;
            case 12:
                getCamera("受损部位", "(请确保道路标线在拍摄画面中。)", R.drawable.car_8, requestCode);
                break;
            default://补拍
                getCamera("受损部位", null, 0, requestCode);
                break;
        }
    }

    //启动相机
    public void getCamera(String title, String titleBottom, int resourceId, int requestCode) {
        Intent intent = new Intent(getContext(), HeNanSurfaceViewCameraActivity.class);
        Bundle bundle = new Bundle();

        if (!StringUtils.isEmpty(title)) {
            bundle.putString("title", title);
        }
        if (!StringUtils.isEmpty(titleBottom)) {
            bundle.putString("titleBottom", titleBottom);
        }

        if (resourceId != 0) {
            bundle.putInt("backGroundResourceId", resourceId);
        }
        intent.putExtras(bundle);

        if (context instanceof MainActivity) {
            ((MainActivity) context).startActivityForResult(intent, requestCode);
        }
    }

    /**
     * 上传图片
     */
    private void uploadImgInfo() {
        if (loadPics == null) {
            loadPics = new ArrayList<Runnable>();
        } else {
            loadPics.clear();
        }
        addPicRunnable(myPicLists, 12, "2");
        addPicRunnable(otherPicLists, 11, "1");
        //为防止后台数据库的重复插入问题，先上传一张，成功后再同时上传剩下的照片
        myHandler.post(loadPics.get(0));
    }

    //添加图片上传的请求任务
    private void addPicRunnable(List<EntityBean> lists, final int imageType, final String ownerType) {
        if (lists == null) {
            return;
        }
        for (int i = 0; i < lists.size(); i++) {
            final String path = lists.get(i).getString("path");
            if (!TextUtils.isEmpty(path)) {
                loadPics.add(new Runnable() {
                    @Override
                    public void run() {
                        useLoadingPic(setEntityBean(path, imageType, ownerType));
                    }
                });
            }
        }
    }

    /**
     * 为上传照片设置bean
     *
     * @param filePath
     * @return
     */
    private EntityBean setEntityBean(String filePath, int currentImageType, String who) {
        EntityBean bean = new EntityBean();
        bean.set("appcaseno", caseNo);
        //经纬度,地址描述
        bean.set("imagelon", mApplication.getLongitude());
        bean.set("imagelat", mApplication.getLatitude());
        bean.set("imageaddress", mApplication.getAddress());
        // 获取图片参数
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(filePath, options);
        bean.set("imagebig", new File(filePath).length());
        bean.set("imageurl", FileUtils.File2byte(new File(filePath), false));
        bean.set("imagewide", Integer.toString(options.outWidth));
        bean.set("imageheigth", Integer.toString(options.outHeight));

        String phoneNumber = mApplication.getLoginInfo().getBean("userinfo").getString("mobilephone");
        if (!StringUtils.isEmpty(phoneNumber)) {
            bean.set("casetelephoe", phoneNumber);
        }
        bean.set("carownertype", who);//1是对方，2是己方
        //拍照类型
        bean.set("shoottype", "2");//定损照片
        //照片类型
        bean.set("imagetype", currentImageType);
        bean.set("imagedate", CommontUtils.getNowTime());
        //areaid
        bean.set("areaid", mApplication.getAreaid());
        bean.set("username", mApplication.getKckpName());
        bean.set("token", mApplication.getToken());
        return bean;
    }

    /**
     * 异步上传图片
     *
     * @param bean
     */
    private void useLoadingPic(EntityBean bean) {
        LoadDataManagerCar.getInstance(context).callService(null, mApplication.getServerUrl(),
                URLConstant.KCKPUPLOADPHOTOS, bean, new LoadDataManagerFather.OnRequestCompleteListener() {
                    @Override
                    public void onSuccess(String key, String service, Object result) {
                        if (result != null) {
                            EntityBean bean = (EntityBean) result;
                            if (bean != null) {
                                String restate = bean.getString("restate");
                                if ("1".equals(restate)) {
                                    curSize++;
                                    if (null != myHandler) {
                                        myHandler.sendEmptyMessage(curSize);
                                    }
                                } else {
                                    String redes = bean.getString("redes");
                                    UiUtil.showToast(context, redes);
                                }
                            }
                        }
                    }

                    @Override
                    public void onError(String key, String service, LoadDataManagerFather.ResultType resultType) {
                        if (null != processDialog) {
                            if (processDialog.isShowing()) {
                                processDialog.dismiss();
                            }
                        }
                        if (resultType == LoadDataManagerFather.ResultType.Failure) {
                            UiUtil.showToast(context, "连接超时，请检查网络后重试。");
                        } else if (resultType == LoadDataManagerFather.ResultType.NoNetWorks) {
                            UiUtil.showToast(context, "无网络连接，请检查您的网络");
                        }
                    }

                    @Override
                    public void onFinished(String key, String service) {

                    }
                });
    }

    @Override
    public void activityReturnBitmap(int requestCode, int resultCode,
                                     Intent data) {
        if (resultCode == MainActivity.RESULT_OK) {
            Bundle bundle = data.getExtras();
            String path = bundle.getString("image");
            if (path == null) {
                UiUtil.showToast(context, "照片拍摄失败！");
                return;
            }
            if (null == curBean) {
                return;
            }
            String type = curBean.getString("type");
            if (TextUtils.equals(type, "-1")) {
                curBean = new EntityBean();//补拍照片
                curBean.set("type", String.valueOf(requestCode));
                if (requestCode == 11) {
                    addPicBean(otherPicLists, curBean);
                } else if (requestCode == 12) {
                    addPicBean(myPicLists, curBean);
                }
            }
            curBean.set("path", path);
            //刷新界面的显示
            if (requestCode == 11) {
                otherAdapter.notifyDataSetChanged();
            } else if (requestCode == 12) {
                myAdapter.notifyDataSetChanged();
            }
        }
    }

    //添加拍照结果
    private void addPicBean(List<EntityBean> lists, EntityBean picBean) {
        if (lists == null) {
            return;
        }
        lists.add(lists.size() - 1, picBean);
        if (lists.size() > SIZE) {
            //拍照数目已达上限则移除+号项
            lists.remove(lists.size() - 1);
        }
    }

    /**
     * 验证图片是否拍摄
     *
     * @return
     */
    private boolean checkTakePhoto(List<EntityBean> picLists) {
        if (picLists == null) {
            return false;
        }
        int size = picLists.size();
        if (size < 1) {
            return false;
        }
        for (int i = 0; i < size; i++) {
            EntityBean bean = picLists.get(i);
            String type = bean.getString("type");
            if (!TextUtils.equals(type, "-1")) {
                String url = bean.getString("url");
                String path = bean.getString("path");
                if (TextUtils.isEmpty(url) && TextUtils.isEmpty(path)) {//照片未拍摄
                    return false;
                }
            }
        }
        return true;
    }

    @Override
    public void OnDestroy() {
        super.OnDestroy();
        regEvent(false);
        if (null != unqualifylist) {
            unqualifylist = null;
        }
        if (null != isqualifylist) {
            isqualifylist = null;
        }
        if (null != myPicLists) {
            myPicLists.clear();
            myPicLists = null;
        }
        if (null != otherPicLists) {
            otherPicLists.clear();
            otherPicLists = null;
        }
        if (null != loadPics) {
            if (null != myHandler) {
                for (Runnable runnable : loadPics)
                    myHandler.removeCallbacks(runnable);
            }
            loadPics.clear();
            loadPics = null;
        }
        if (null != processDialog) {
            processDialog.dismiss();
            processDialog = null;
        }
        otherAdapter = null;
        otherGView = null;
        myAdapter = null;
        if (null != myGView) {
            myGView.setAdapter(null);
            myGView = null;
        }
        myHandler = null;
        view = null;
    }
}